from package.fastapi.crud import Crud
from model.model import Devops, Source
from package.task import task
from .job import devops_job


class DevopsTask(Crud):
    """需要修改 心跳 指标监测等任务"""
    HeartBeatPrefix = 'heartbeat_'
    MetricPrefix = 'metric_'

    def add_heartbeat_job(self, item):
        """添加心跳任务"""
        if not item.heartbeat_interval:
            return

        task.scheduler.add_job(func=devops_job.heartbeat, id=f'{self.HeartBeatPrefix}{item.id}',
                               name=f'{self.HeartBeatPrefix}{item.id}', kwargs={'devops': item}, trigger='interval',
                               minutes=item.heartbeat_interval, replace_existing=True)

    def update_heartbeat_job(self, item):
        """添加心跳任务"""
        if not item.heartbeat_interval:
            self.delete_heartbeat_jobs([item.id])
            return
        self.add_heartbeat_job(item)

    def add_metric_job(self, item):
        if not item.metric_interval:
            return

        task.scheduler.add_job(func=devops_job.metric, id=f'{self.MetricPrefix}{item.id}',
                               name=f'{self.MetricPrefix}{item.id}', kwargs={'devops': item}, trigger='interval',
                               minutes=item.metric_interval, replace_existing=True)

    def update_metric_job(self, item):
        """添加心跳任务"""
        if not item.metric_interval:
            self.delete_metric_jobs([item.id])
            return
        self.add_metric_job(item)

    def delete_heartbeat_jobs(self, ids):
        for id in ids:
            try:
                task.scheduler.remove_job(f'{self.HeartBeatPrefix}{id}')
            except Exception as e:
                pass

    def delete_metric_jobs(self, ids):
        for id in ids:
            try:
                task.scheduler.remove_job(f'{self.MetricPrefix}{id}')
            except Exception as e:
                pass

    def create_item(self, session, body, commit=True):
        item = super(DevopsTask, self).create_item(session, body, commit=False)
        self.add_heartbeat_job(item)
        self.add_metric_job(item)
        session.commit()
        return item

    def update_item(self, session, update: dict, id: str = None, filter_: list = None, commit=True):
        item = super(DevopsTask, self).update_item(session, update=update, id=id, filter_=filter_, commit=False)
        self.update_heartbeat_job(item)
        self.update_metric_job(item)
        session.commit()
        return item

    def delete_items(self, session, ids, commit=True):
        self.delete_heartbeat_jobs(ids)
        self.delete_metric_jobs(ids)
        return super(DevopsTask, self).delete_items(session, ids)


devops = DevopsTask(model=Devops, keyword_fields=['name', 'ip'])
source = Crud(model=Source, keyword_fields=['name', 'ip'])
